<template>
    <div class="app-container" v-loading.fullscreen.lock="loading">
        <div>
            <el-form class="lookForm" label-width="120px">
                <el-row>
                    <el-col :span="6">
                        <el-form-item label="学号">
                            <el-input size="mini" v-model="search.stuNo"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label-width="10px">
                            <el-button icon="el-icon-search" type="primary" size="mini" @click="doSearch">搜索</el-button>
                            <el-button icon="el-icon-refresh" size="mini" @click="doRefresh">重置</el-button>
                            <el-button icon="el-icon-upload2" type="primary" size="mini"
                                @click="importVClick">导入</el-button>
                            <el-button icon="el-icon-download" size="mini" type="primary"
                                @click="exportV = true">导出</el-button>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item label="班级">
                            <el-select style="width: 100%;" size="mini" @change="changeSelect"
                                v-model="search.className">
                                <el-option v-for="(v, i) in class_list" :key="i" :label="v.className"
                                    :value="v.className"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="学年">
                            <el-select style="width: 100%;" size="mini" @change="changeYearSelect"
                                v-model="search.stuYearName">
                                <el-option v-for="(v, i) in stu_year_list" :key="i" :label="v.stuYearName"
                                    :value="v.stuYearName"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>

        <el-table v-loading="loading" :data="data_list" style="width:100%;margin-top: -20px;">
            <el-table-column v-if="search.className != '' || search.stuYearName != ''" label="#" align="center"
                width="80">
                <template slot-scope="scope">
                    {{ scope.$index + 1 }}
                </template>
            </el-table-column>
            <el-table-column prop="stuYearName" label="学年" align="center" />
            <el-table-column prop="className" label="班级" align="center" width="250" />
            <el-table-column prop="stuName" label="学生姓名" align="center" />
            <el-table-column prop="stuNo" label="学号" align="center" />
            <el-table-column prop="score" label="综合评价成绩" align="center" />
            <el-table-column label="学生状态" align="center" prop="status">
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.srs_stu_status" :value="scope.row.status" />
                </template>
            </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="listInfo" />

        <!-- 导入学生成绩 -->
        <el-dialog title="导入" :visible.sync="importV" :before-close="handleClose" width:60 center
            style="text-align: center;">
            <el-row type="flex" class="row-bg" justify="space-around">
                <el-upload center class="upload-demo" drag :auto-upload="false" :limit="1" :on-exceed="handleExceed"
                    action="" :file-list="fileList" :on-change="fileChoose">
                    <i class="el-icon-upload"></i>
                    <div class="el-upload__text">将文件拖到此处，或<em>点击选择</em></div>
                    <div class="el-upload__tip" slot="tip">只能上传xlsx/xls文件 <el-link @click="downloadMode" type="primary"
                            size="mini">下载模板</el-link>
                    </div>
                </el-upload>
            </el-row>
            <el-form>
                <el-form-item label="学年">
                    <el-select v-model="stu_year_import" placeholder="请选择学年">
                        <el-option v-for="(v, i) in stu_years" :key="i" :label="v.stuYearName" :value="v.id">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <el-table border :data="tableData.slice((currentPage - 1) * pagesize, currentPage * pagesize)"
                :stripe="true" :current-page.sync="currentPage" max-height="550" style="width: 100%">
                <el-table-column prop="stuNo" label="学号" width="180">
                </el-table-column>
                <el-table-column prop="ce_score" label="综合评价成绩">
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                    :page-sizes="[10, 15, 20]" :page-size="pagesize" layout="total, sizes, prev, pager, next, jumper"
                    :total="importTotal">
                </el-pagination>
            </div>


            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="doImport()">导 入</el-button>
            </span>
        </el-dialog>
        <el-dialog title="选择导出" :visible.sync="exportV" width="600px" append-to-body>
            <el-form label-width="120px">
                <el-form-item label="学年">
                    <el-select id="stuYearId" size="mini" style="width: 400px;" v-model="exportForm.stuYearId"
                        placeholder="请选择学年">
                        <el-option :key="i" v-for="(v, i) in stu_year_list" :value="v.id"
                            :label="v.stuYearName"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="班级">
                    <el-select style="width: 400px;" size="mini" v-model="exportForm.classId">
                        <el-option v-for="(v, i) in class_list" :key="i" :label="v.className"
                            :value="v.classId"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="">
                    <el-button size="mini" @click="toExport">导出</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>
<script>
import { listCe, listAllCe } from "@/api/stuCQS/basedata/teacher";
import { isEmpty } from "@/api/helpFunc";
import { listOwnClass } from "@/api/stuCQS/info-fill/stu_eva_task";
import { listEnableYear as listAllStuYear } from "@/api/stuCQS/basedata/year";
import * as XLSX from 'xlsx';
import { workbook2blob, openDownloadDialog, file2Xce } from "@/api/helpFunc";
import { importExcel, toExport } from "@/api/stuCQS/info-fill/ceScore";
import { listAllYear as listStuYear } from "@/api/stuCQS/basedata/year";

export default {
    name: "ce",
    dicts: ['srs_stu_status'],
    data() {
        return {
            stu_year_list: [],

            queryParams: {
                pageNum: 1,
                pageSize: 10,
            },
            loading: false,
            total: 0,
            data_list: [],
            all_list: [],
            search: {
                stuNo: "",
                className: "",
                stuYearName: ""
            },
            class_list: [],

            stu_year_import: null,
            fileList: [],
            tableData: [],
            currentPage: 1,
            pagesize: 10,
            importTotal: 0,
            //学年下拉框的内容
            stu_years: [],
            //导入学生成绩的弹窗控制
            importV: false,
            exportV: false,
            exportForm: {
                stuYearId: null,
                classId: null,
            },
        }
    },
    created() {
        this.listStuYear();

        this.listOwnClass();
        this.listAllInfo();
        this.listInfo();
        this.listAllStuYear();

    },
    methods: {
        async listStuYear() {
            let res = await listStuYear();
            if (res.code == 200) {
                this.stu_year_list = [...res.data];
                console.log(this.stu_year_list)
            }
        },

        // 下载申请信息模板
        downloadMode() {
            // 第一个sheet工作簿，如果需要创建多个，对应let多个sheetXdata即可
            let sheet1data = [
                {
                    stuNo: "20210001",
                    ce_score: 96,
                    "操作提示": "第一条为样板数据，stuNo表示学号，ce_score表示学生的综合评价成绩"
                },
            ];
            // let sheet2data = []; // 第二个sheet工作簿
            // 转换sheet格式
            var sheet1 = XLSX.utils.json_to_sheet(sheet1data);
            // 创建一个新的空的workbook      
            var wb = XLSX.utils.book_new();
            // 为每一个工作簿设置名称并添加到workbook（excel表）中
            XLSX.utils.book_append_sheet(wb, sheet1, "综合评价导入模板");
            const workbookBlob = workbook2blob(wb);  // 辅助函数workbook2blob
            // 下载文档并添加文件名称
            openDownloadDialog(workbookBlob, "综合评价导入模板.xlsx");  // 辅助函数openDownloadDialog
        },

        //导入学生成绩
        async doImport() {
            if (this.stu_year_import == null) {
                this.$message.info("请选择学年");
                return;
            }
            let sdata = [];
            let temp = [...this.tableData];
            temp.map(v => {
                let ce_score = v.ce_score;
                if (ce_score > 100) {
                    ce_score = 100;
                }
                let temp1 = {
                    ceScore: ce_score,
                    stuNo: v.stuNo,
                    stuYearId: this.stu_year_import
                };
                sdata.push(temp1);
            });

            let jsonStr = JSON.stringify(sdata);
            this.loading = true;
            let res = await importExcel(jsonStr);
            this.loading = false;

            this.$message(res.msg);
            this.doRefresh();

            this.importV = false;
            this.fileList = [];
            this.listOwnClass();
            this.listAllInfo();
            this.listInfo();
            this.listAllStuYear();
        },
        handleSizeChange(val) {
            this.pagesize = val;
        },
        handleCurrentChange(val) {
            this.currentPage = val;
        },
        async fileChoose(file, fileList) {
            this.fullscreenLoading = true;
            let data = await this.handleData(file);
            this.tableData = data;
            this.importTotal = data.length;
        },
        handleData(file) {
            let reader = new FileReader();
            reader.readAsArrayBuffer(file.raw);
            return new Promise((resolve, reject) => {
                reader.onload = (e) => {
                    let data = e.target.result;
                    let workbook = XLSX.read(data, { //手动转化
                        type: 'binary'
                    });
                    //获取json格式的Excel数据
                    let jsonData = XLSX.utils.sheet_to_json(workbook.Sheets[workbook
                        .SheetNames[0]], {
                        defval: 'null' //单元格为空时的默认值
                    });
                    resolve(jsonData);
                };
            })
        },
        handleExceed(files, fileList) {
            this.$message.warning(
                `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`
            );
        },
        handleClose(done) {
            this.$confirm('确认关闭？').then(_ => {
                this.excelData = [];
                this.fileList = [];
                done();
            }).catch(_ => { });
        },

        //点击导入弹窗按钮
        importVClick() {
            this.importV = true;
        },
        //列出所有学年
        async listAllStuYear() {
            let res = await listAllStuYear();
            this.stu_years = [...res.rows];
        },


        async listAllInfo() {
            this.loading = true;
            let res = await listAllCe();
            this.loading = false;
            if (res.code == 200) {
                this.all_list = [...res.data];
            }
        },
        async listInfo() {
            this.loading = true;
            let res = await listCe(this.queryParams);
            this.loading = false;
            if (res.code == 200) {
                this.data_list = [...res.rows];
                this.total = res.total;
            }
        },

        changeSelect() {
            let className = this.search.className;
            let stuYearName = this.search.stuYearName;

            if (!isEmpty(className)) {
                let temp1 = [];
                let temp2 = [...this.all_list];
                temp2.map(x => {
                    if (!isEmpty(stuYearName)) {
                        if (x.className == className && x.stuYearName == stuYearName) {
                            temp1.push(x);
                        }
                    } else {
                        if (x.className == className) {
                            temp1.push(x);
                        }
                    }
                });
                this.total = 0;
                this.queryParams.pageSize = temp1.length;
                this.data_list = [...temp1];
                return;
            }
        },
        changeYearSelect() {
            let className = this.search.className;
            let stuYearName = this.search.stuYearName;
            if (!isEmpty(stuYearName)) {
                let temp1 = [];
                let temp2 = [...this.all_list];
                temp2.map(x => {
                    if (!isEmpty(className)) {
                        if (x.stuYearName == stuYearName && x.className == className) {
                            temp1.push(x);
                        }
                    } else {
                        if (x.stuYearName == stuYearName) {
                            temp1.push(x);
                        }
                    }

                });
                this.total = 0;
                this.queryParams.pageSize = temp1.length;
                this.data_list = [...temp1];
                return;
            }
        },
        doRefresh() {
            this.search.stuNo = "";
            this.search.className = "";
            this.search.stuYearName = "";

            this.queryParams.pageSize = 10;
            this.listInfo();
        },
        async doSearch() {
            let stuNo = this.search.stuNo;
            if (!isEmpty(stuNo)) {
                let temp1 = [];
                let temp2 = [...this.all_list];
                temp2.map(x => {
                    if (x.stuNo == stuNo) {
                        temp1.push(x);
                    }
                });
                this.total = 0;
                this.queryParams.pageSize = temp1.length;
                this.data_list = [...temp1];
                return;

            }
        },
        async listOwnClass() {
            this.loading = true;
            let res = await listOwnClass();
            this.loading = false;
            if (res.code == 200) {
                this.class_list = [...res.data];
            }
        },
        async toExport() {
            if (isEmpty(this.exportForm.stuYearId)) {
                this.$message("请选择学年");
                return;
            }
            if (isEmpty(this.exportForm.classId)) {
                this.$message("请选择班级");
                return;
            }

            this.loading = true;
            let res = await toExport(this.exportForm);
            this.loading = false;
            if (res.code == 200) {
                let data = res.data;
                const header = ['1学年', '2学院', '3专业', '4班级', '5学号', '6姓名', '7综合评价', '8班级排名', '9专业排名', '10学生状态', '11导出时间'];
                const header_zh = {
                    '1学年': '1学年',
                    '2学院': '2学院',
                    '3专业': '3专业',
                    '4班级': '4班级',
                    '5学号': '5学号',
                    '6姓名': '6姓名',
                    '7综合评价': '7综合评价',
                    '8班级排名': '8班级排名',
                    '9专业排名': '9专业排名',
                    '10学生状态': '10学生状态',
                    '11导出时间': '11导出时间'
                };

                const arrayWithHeader = [header_zh, ...data];

                var sheet1 = XLSX.utils.json_to_sheet(arrayWithHeader,
                    {
                        header: header,
                        skipHeader: true
                    });
                sheet1["!cols"] = [
                    { wch: 15 },
                    { wch: 20 },
                    { wch: 20 },
                    { wch: 25 },
                    { wch: 12 },
                    { wch: 12 },
                    { wch: 12 },
                    { wch: 12 },
                    { wch: 12 },
                    { wch: 12 },
                    { wch: 12 },
                    { wch: 12 },
                    { wch: 12 },
                    { wch: 12 }
                ];

                // 创建一个新的空的workbook
                var wb = XLSX.utils.book_new();
                // 为每一个工作簿设置名称并添加到workbook（excel表）中
                XLSX.utils.book_append_sheet(wb, sheet1, "综合评价");
                const workbookBlob = workbook2blob(wb);  // 辅助函数workbook2blob
                // 下载文档并添加文件名称
                openDownloadDialog(workbookBlob, "综合评价.xlsx");  // 辅助函数openDownloadDialog

            }
        },
    }
}
</script>
<style scoped lang="scss">
.lookForm {
    .el-form-item {
        margin-bottom: 5px;
    }
}
</style>